# -*- coding: utf-8 -*-
from django.forms.widgets import Select, HiddenInput, TextInput
from django.utils.safestring import mark_safe

from .. import utils

class Link(Select):
    """
    Use this widget if you want to show selection choices as links
    (and not as options of a select box).
    """
    def __init__(self, base_url=u'', *args, **kwargs):
        super(Link, self).__init__(*args, **kwargs)
        self.querydict = None
        self.base_url = base_url
        
    def _get_link(self, name, value, label):
        querydict = self.querydict.copy()
        if value:
            querydict[name] = value
            url = u"?%s" % querydict.urlencode()
        else:
            url = utils.url_without_key(name, querydict)
        return u"""<a class="yaletter" href="%s%s">%s</a>""" % (self.base_url, url, label)
        
    def render(self, name, value, attrs=None, choices=()):
        if not choices:
            choices = self.choices
        if value is None:
            value = u""
        # a hidden input with current value is rendered for mantaining
        # current link choice                  
        output = [HiddenInput().render(name, value)]
        # the template for selected choice
        template = u"""<span class="yaselected"><strong>%s</strong></span>"""
        for k, v in choices:
            if k == value:
                output.append(template % v)
            else:
                output.append(self._get_link(name, k, v))
        return mark_safe(u"&nbsp;".join(output))
        
        
class Search(TextInput):
    """
    Search widget. It is just like a normal *TextInput** but it append
    at the end of ther render output a link to remove current search.
    """
    def __init__(self, *args, **kwargs):
        super(Search, self).__init__(*args, **kwargs)
        self.querydict = None
        self.remove_label = u""
        
    def add_remove_link(self, output, url, label):
        """
        Adds the remove link to the html output.
        This is only used when there is actually a search.
        """
        return u"""%s&nbsp;(<a href="%s">%s</a>)""" % (output, url, label)
    
    def render(self, name, value, attrs=None):
        output = super(Search, self).render(name, value, attrs)
        if value:
            url = utils.url_without_key(name, self.querydict)
            output = self.add_remove_link(output, url, self.remove_label)
        return mark_safe(output)
